import 'dart:convert';
import 'dart:ui';

import 'package:get/get.dart';
import 'package:sainbainu/common/apis/message_api.dart';
import 'package:sainbainu/common/enums/message_type.dart';
import 'package:sainbainu/common/models/response/message_num_response.dart';
import 'package:sainbainu/common/repositories/message_repository.dart';
import 'package:sainbainu/common/services/jpush.dart';
import 'package:sainbainu/common/services/storage.dart';
import 'package:sainbainu/common/services/user.dart';
import 'package:sainbainu/common/values/storage_keys.dart';

class MessageService extends GetxService {
  static MessageService get to => Get.find();

  MessageService(this._messageRepository);

  /// 消息仓库
  final MessageRepository _messageRepository;

  /// 未读消息数量
  final _messageNumResponse = MessageNumResponse().obs;
  Rx<MessageNumResponse> get messageNumResponse => _messageNumResponse;

  @override
  void onInit() {
    super.onInit();
    if (UserService.to.isLogin.value) {
      getMessageNum();
    }
  }

  /// 获取未读消息数量
  Future<void> getMessageNum() async {
    var res = await _messageRepository.getMessageNum();
    _messageNumResponse.value = res;
    JpushService.to.setBadge(res.totalNum);
  }

  /// 清除消息数量
  Future<void> clearMessageNum(MessageType msgType) async {
    await _messageRepository.clearMessageNum(msgType);
    JpushService.to.setBadge(0);
  }
}
